/*
 *  Copyright 2012 yura.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */

package org.opu.pc.publications_analysis;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.util.Scanner;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.IOUtils;
import org.opu.pc.domain.domains.Publication;
import org.opu.pc.domain.domains.Publisher;
import org.opu.pc.ui.util.Logger;
import org.opu.pc.util.ArraySet;
import org.opu.pc.util.StringUtil;

/**
 *
 * @author yura
 */
public abstract class FileProcessor {

    final static Logger logger = Logger.create(FileProcessor.class);
    private static final String SPACE = "\\s+";
    private static final String UpLater = "[А-ЯЇІЄЭЁҐ]";
    private static final String Initial = UpLater + "\\.";
    private static final String DnLater = "[а-яїієэёґ]";
    private static final String Initials = Initial + SPACE + Initial;
    private static final String FullInitials = UpLater + DnLater + "+" + SPACE + Initials;
    private static final Pattern FullInitialsPattern = Pattern.compile(FullInitials);

    protected abstract String getName();

    protected abstract String getTextDataFromFile(InputStream file,
            StringBuffer document, int lineNum) throws IOException;

    public Publication processFile(InputStream file, StringBuffer document,
            int lineNum) throws IOException {
        Publication publication = new Publication();
        
        String textData = getTextDataFromFile(file, document, lineNum);
        IOUtils.closeQuietly(file);

        Scanner scanner = new Scanner(new StringReader(textData));
        String nextLine;
        Set<Publisher> publishers = new ArraySet<Publisher>();

        try{
            // read theme
            nextLine = scanner.nextLine();
            if (StringUtil.contains(nextLine, "^\\s*УДК")){
                // nextLine.startsWith("\\s*УДК")
                nextLine = scanner.nextLine();
            }
            while(nextLine.trim().isEmpty()){
                nextLine = scanner.nextLine();
            }
            publication.setName(nextLine);

            while((nextLine = scanner.nextLine()).trim().isEmpty());

            // read publishers
            if (StringUtil.contains(nextLine, Initials)){
                // It's can be:
                // 1) Дунько Ю. С., Поточняк Я. В.
                // 2) Дунько Ю.С.
                //    к.т.н.,доценткаф.СПЗБлажкоА.А.
                String[] split = nextLine.split("," + SPACE);
                if (split.length > 1) {
                    for (String string : split) {
                        addPublisher(publishers, string);
                    }
                } else {
                    do {
                        Matcher matcher = FullInitialsPattern.matcher(nextLine);
                        matcher.find();
                        addPublisher(publishers, matcher.group());
                        while((nextLine = scanner.nextLine()).trim().isEmpty());
                    } while (StringUtil.contains(nextLine, Initials)
                            && publishers.size() < 4);
                }
            } else if (nextLine.split(SPACE).length == 2){
                // It's can be:
                // 1) Дунько Юрий
                // 2) Дунько Юрий
                //    Поточняк Яна
                do {
                    addPublisher(publishers, nextLine);
                } while ((nextLine = scanner.nextLine()).split(SPACE).length == 2
                            && publishers.size() < 4);
            }

        } catch (Exception ex){
            logger.error(ex);
        }
        publication.setPublishers(publishers);

        return publication;
    }

    private void addPublisher(Set<Publisher> publishers, String string) {
        Publisher p = new Publisher();
        String[] initials = string.split(SPACE, 3);
        if (initials.length > 0) {
            p.setSecondName(initials[0]);
        }
        if (initials.length > 1) {
            p.setName(initials[1]);
        }
        if (initials.length > 2) {
            p.setLastName(initials[2]);
        } else if (initials.length > 1 && initials[1].length() == 4
                && initials[1].charAt(1) == '.' && initials[1].charAt(3) == '.'){
            p.setName(initials[1].substring(0, 2));
            p.setLastName(initials[1].substring(2, 4));
        }
        publishers.add(p);
    }
}
